using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Threading;

namespace FEZFirmwareUpdater
{
    public class Updater
    {
        public static string CheckForFEZDevice(string portName)
        {
            using (SerialPort serialPort = new SerialPort(portName))
            {
                serialPort.Open();
                serialPort.Write("V"); // Get version
                Thread.Sleep(20);

                string existing = serialPort.ReadExisting();
                if (string.IsNullOrEmpty(existing)) return null;

                string[] split = existing.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                if (split.Length != 2) return null;
                if (split[1] != "BL") return null;

                return split[0];
            }
        }

        public static int UpdateFirmware(BackgroundWorker backgroundWorker, string portName, string filePath)
        {
            int xmodemTransmit = -10;

            try
            {
                byte[] buffer;

                // Fix by Ramon
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    int length = Convert.ToInt32(fs.Length);
                    buffer = new byte[length];
                    fs.Read(buffer, 0, length);
                }

                int totalPackets = buffer.Length / 1024 + 1;
                int packetsSent = 0;
                using (SerialPort serialPort = new SerialPort(portName, 115200))
                {
                    serialPort.ReadTimeout = serialPort.WriteTimeout = 1000;
                    serialPort.Open();
                    serialPort.Write("X"); // Start transfer
                    Thread.Sleep(20);

                    serialPort.DiscardInBuffer();

                    XModem xModem = new XModem(serialPort);
                    xModem.PacketSent += (sender, args) =>
                                             {
                                                 packetsSent++;
                                                 backgroundWorker.ReportProgress(100 * packetsSent / totalPackets);
                                             };
                    xmodemTransmit = xModem.XmodemTransmit(buffer, buffer.Length, true);

                    backgroundWorker.ReportProgress(100);
                }
            }
            catch {}

            return xmodemTransmit;
        }
    }
}